package com.meilai.project.service.administration.seal.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.administration.seal.UseSealFlowDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.dto.workflow.WorkFlowExtraCheckDTO;
import com.meilai.project.entity.administration.seal.UseSealFlow;
import com.meilai.project.entity.administration.seal.UseSealFlowAttachment;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.administration.seal.UseSealFlowMapper;
import com.meilai.project.service.administration.seal.UseSealFlowAttachmentService;
import com.meilai.project.service.administration.seal.UseSealFlowService;
import com.meilai.project.service.system.impl.UserServiceImpl;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.administration.seal.UseSealFlowVO;
import com.meilai.project.vo.system.UserForWFVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用印申请表 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-01-24
 */
@Service
public class UseSealFlowImpl extends ServiceImpl<UseSealFlowMapper, UseSealFlow> implements UseSealFlowService {

    @Autowired
    private UseSealFlowAttachmentService useSealFlowAttachmentService;

    @Override
    public Page<UseSealFlow> selectPage(Integer current_page, Integer page_size, Boolean is_manage_page, String name, Long seal_type_id, String seal_type_name, String post, Long company_id) {
        Page<UseSealFlow> page = new Page<>(current_page, page_size);
        Long userId = ThreadLocalUserUtil.get().getId();
        page.setRecords(baseMapper.page(page, is_manage_page ? null : userId, name, seal_type_id, seal_type_name, post, company_id));
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(UseSealFlowDTO dto) {
        // 保存至草稿箱
        int flowResult = saveAndBegin(dto, true);
        if (flowResult != 1) throw new CommonException("保存至草稿箱失败，请联系管理员！");
        else return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean begin(UseSealFlowDTO dto) {
        // 提交
        int flowResult = saveAndBegin(dto, false);
        if (flowResult == 1) {
            // 仍在流程中
            return true;
        } else if (flowResult == 2) {
            // 无审批节点，直接结束
            return true;
        } else {
            throw new CommonException("提交失败，请联系管理员！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pass(WorkFlowExtraCheckDTO dto) {
        // 通过
        int flowResult = passAndBack(dto, true);
        return flowResult == 1 || flowResult == 2;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean returnBack(WorkFlowExtraCheckDTO dto) {
        // 驳回
        int flowResult = passAndBack(dto, false);
        return flowResult == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        int flowResult = deleteAndActualDel(id, false);
        if (flowResult != 1) throw new CommonException("删除失败，请联系管理员！");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean actualDelete(Long id) {
        int flowResult = deleteAndActualDel(id, true);
        if (flowResult != 1) throw new CommonException("彻底删除失败，请联系管理员！");
        return true;
    }

    @Override
    public UseSealFlowVO one(Long id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        UseSealFlow flow = this.getById(id);
        UseSealFlowVO result = new UseSealFlowVO();
        BeanUtils.copyProperties(flow, result);
        result.setCan_check(WorkFlowUtil.canCheckData(userId, flow));

        // 处理子表数据
        result.setUseSealFlowAttachmentList(useSealFlowAttachmentService.list(Wrappers.<UseSealFlowAttachment>lambdaQuery().eq(UseSealFlowAttachment::getUse_seal_flow_id, id)));

        return result;
    }

    // 保存 和 提交 抽出相同代码
    private int saveAndBegin(UseSealFlowDTO dto, boolean isSave) {
        // 获取当前人的id和部门id
        UserForWFVO user = UserServiceImpl.getUserForWF(dto);

        // 业务数据
        UseSealFlow temp = new UseSealFlow();
        BeanUtils.copyProperties(dto, temp);

        // 设置流程字段，flow_type请自行对应“dict_flow_type”表中的id， 比如当前入职流程（考察登记流程）的id是5
        String flow_title = dto.getApplicant_name() + "用章申请"; // 审批流程的名称，需要根据实际业务自行确定
        FlowBusinessDataSuperEntity fbdse = WorkFlowUtil.getStartSuperDataEntity(
                user.getUser_id(),  // 当前用户id
                user.getDep_id(), // 提交的部门id
                11, // 流程类型id，“dict_flow_type”表中的id
                flow_title // 自定义的流程标题
        );
        BeanUtils.copyProperties(fbdse, temp);

        // 是否为新数据
        // 新数据时，前端不传业务数据id
        // 非新数据时，即来源是“草稿箱”、“已删除”、“被退回”时，前端需要传入业务数据id
        boolean isFirst = (dto.getId() == null);

        // 由于流程字段含有id，会覆盖数据，此处需要手动setId
        if (!isFirst) temp.setId(dto.getId());


        boolean flag = isFirst ? save(temp) : updateById(temp);

        // 保存或者提交成功 插入字表数据
        // 删除旧的
        useSealFlowAttachmentService.remove(Wrappers.<UseSealFlowAttachment>lambdaQuery().eq(UseSealFlowAttachment::getUse_seal_flow_id, temp.getId()));

        if (CollectionUtils.isNotEmpty(dto.getUseSealFlowAttachmentList())) {
            dto.getUseSealFlowAttachmentList().forEach(item -> {
                item.setId(null);
                item.setUse_seal_flow_id(temp.getId());
            });
            useSealFlowAttachmentService.saveBatch(dto.getUseSealFlowAttachmentList());
        }
        if (!flag) throw new CommonException("保存失败");

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<UseSealFlow, UseSealFlowMapper>(temp.getId(), user.getUser_id(), UseSealFlow.class);

        // 审批流程id
        // 新数据,传0L
        // 非新数据,根据数据id,查找wfData_id
        Long wfData_id = isFirst ? 0L : wfu.getWfDataId(dto.getId());
        // 旧数据记录留存
        UseSealFlow old_data = isFirst ? new UseSealFlow() : temp;

        return isSave ? wfu.SaveDraft(wfData_id) : wfu.Begin(wfData_id, "", old_data);
    }

    // 通过 和 驳回 抽出相同代码
    private int passAndBack(WorkFlowExtraCheckDTO dto, boolean isPass) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();
        // 业务数据
        UseSealFlow temp = getById(dto.getId());

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<UseSealFlow, UseSealFlowMapper>(dto.getId(), userId, UseSealFlow.class);

        // 审批入参类
        WorkFlowCheckDTO checkDTO = WorkFlowCheckDTO.getWorkFlowCheckDTO(
                temp.getFlow_current_node_id(), // 当前节点id
                temp.getFlow_json(), // 流程json
                dto.getWf_check_opinion(), // 审批意见
                dto.getWf_check_sign_url(), // 审批签名链接
                JSONObject.toJSONString(temp) // 旧数据留存
        );

        // 审批
        return isPass ? wfu.ToNext(checkDTO) : wfu.ReturnBack(checkDTO);
    }

    // 删除 和 彻底删除 抽出相同代码
    private int deleteAndActualDel(Long id, boolean isActual) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<UseSealFlow, UseSealFlowMapper>(id, userId, UseSealFlow.class);

        // 流程id
        Long wfData_id = wfu.getWfDataId(id);

        return isActual ? wfu.ActualDelete(wfData_id) : wfu.Delete(wfData_id);
    }
}
